﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DPLParser.DPLILCode;
using Irony.Parsing;

namespace DPLParser.DPLNodeParser.DPLScriptTreeNodeMappers.Implementations
{
    public class DPLFunctionCallExtractor : AbstractDPLScriptItemExtractor<DPLFunctionCall>
    {
        public DPLFunctionCallExtractor(ParseTreeNode originalNode)
            : base(originalNode)
        {
            
        }

        public override DPLFunctionCall GetItem()
        {
            ParseTreeNodeList memberOperations = OriginalTreeNode.GetNodes("*.DirectOperatorName.");
            Queue<ParseTreeNode> queuedMemberOperations = new Queue<ParseTreeNode>(memberOperations);
            return GetCall(queuedMemberOperations);
        }

        private DPLFunctionCall GetCall(Queue<ParseTreeNode> CallTreeNodes)
        {
            if (CallTreeNodes.Count == 0)
                return null;
            else
            {
                DPLFunctionCall aFunctionCall = new DPLFunctionCall();
                var callNode = CallTreeNodes.Dequeue();
                var operationNode = callNode.ChildNodes[0];
                if (operationNode.Term.Name == DPLFunctionCall.DPLOperation.CALLER.ToString())
                    aFunctionCall.FunctionOperation = DPLFunctionCall.DPLOperation.CALLER;
                else if (operationNode.Term.Name == DPLFunctionCall.DPLOperation.CONTR.ToString())
                    aFunctionCall.FunctionOperation = DPLFunctionCall.DPLOperation.CONTR;
                else if (operationNode.Term.Name == DPLFunctionCall.DPLOperation.TYPE.ToString())
                    aFunctionCall.FunctionOperation = DPLFunctionCall.DPLOperation.TYPE;

                if (CallTreeNodes.Count > 0)
                {
                    DPLFunctionCall nestedFuncCall = GetCall(CallTreeNodes);
                    aFunctionCall.NestedCall = nestedFuncCall;
                }
                return aFunctionCall;
            }
        }
    }
}
